import {Action, Callback, DatetimeProjectItemImpl, NoExecutor, ProjectArgsImpl, ProjectItemImpl} from './Types'
import {isEmpty, isNil, max} from 'licia'
import {i18n, sentenceKey} from './i18n'
import {score} from './Utils'
const $ = require('licia/$')

const emptyTips: () => ProjectItemImpl = () => {
    return {
        id: 'cc1b114e-5d1a-40df-b117-8c2cd7ddffa4',
        title: i18n.t(sentenceKey.emptyTipsTitle),
        description: i18n.t(sentenceKey.emptyTipsDesc),
        icon: 'info.png',
        searchKey: [],
        exists: true,
        command: new NoExecutor(),
    }
}

export class AllProjectArgs extends ProjectArgsImpl {
    placeholder = '通过项目名快速查找项目'

    override enter(action: Action, callback: Callback<ProjectItemImpl>): void {
        super.enter(action, callback)
        this.getProjectItems(utools.getNativeId())
            .then(result => {
                const items = isEmpty(result) ? [emptyTips()] : result;
                callback(items);
            }).catch(error => {
                console.log(error)
                utools.showNotification(error.message)
                utools.copyText(error.message)
                utools.showNotification(i18n.t(sentenceKey.errorInfoToClipboard))
            })
    }

    search = (action: Action, searchText: string, callback: Callback<ProjectItemImpl>) => {
        if (isEmpty(searchText)) {
            if (isEmpty(this.projectItemCache)) {
                callback([emptyTips()])
            } else {
                callback(this.projectItemCache)
            }
        } else {
            let text = searchText.toLocaleLowerCase()
            if (this.context?.enableFuzzyMatch) {
                callback(this.projectItemCache
                    .map(item => {
                        item.score = max(...item.searchKey.map(k => score(k, text)))
                        return item
                    })
                    .filter(item => item.score !== 0)
                    .sort((a, b) => b.score! - a.score!),
                )
            } else {
                callback(this.projectItemCache.filter(item => {
                    for (let key of item.searchKey) {
                        if (key.toLowerCase().indexOf(text) > -1) {
                            return true
                        }
                    }
                    return false
                }))
            }
        }
    }

    select = (action: Action, item: ProjectItemImpl, callback: Callback<ProjectItemImpl>) => {
        if (item.id === emptyTips().id) {
            utools.redirect('Setting', '')
            return
        }
        if (!item.exists) {
            utools.showNotification(i18n.t(sentenceKey.filePathNonExistsTips))
            return
        }
        if (this.context?.enableOpenNotification ?? false) {
            utools.showNotification(`${i18n.t(sentenceKey.fileOpening)}: ${item.title}`)
        }
        item.command.execute()
    }
}

export class AllProjectSortByTimeArgs extends AllProjectArgs {
    override compare(p1: DatetimeProjectItemImpl, p2: DatetimeProjectItemImpl): number {
        return p2.datetime - p1.datetime
    }
}

export class AllProjectSortByTitleArgs extends AllProjectArgs {
    override compare(p1: ProjectItemImpl, p2: ProjectItemImpl): number {
        if (!isNil(p1?.['title']) && !isNil(p2?.['title'])) {
            let a = p1['title'], b = p2['title']
            if (a === b) return 0
            if (a > b) return 1
            if (a < b) return -1
            return 0
        }
        return 0
    }
}
